package com.bymboy.emos.wx.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bymboy.emos.wx.db.dao.TbMeetingDao;
import com.bymboy.emos.wx.db.dao.TbUserDao;
import com.bymboy.emos.wx.db.pojo.TbMeeting;
import com.bymboy.emos.wx.exception.EmosException;
import com.bymboy.emos.wx.service.MeetingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Package: com.bymboy.emos.wx.service.impl
 * @ClassName: MeetingServiceImpl
 * @Author: My
 * @CreateTime: 2021/10/12 8:45
 * @Description:
 */
@Service
@Slf4j
public class MeetingServiceImpl implements MeetingService {

    @Resource
    private TbMeetingDao meetingDao;

    @Resource
    private TbUserDao userDao;

    @Value("${emos.code}")
    private String code;

    @Value("${workflow.url}")
    private String workflow;

    @Value("${emos.recieveNotify}")
    private String recieveNotify;

    @Override
    public void insertMeeting(TbMeeting entity) {
        //保存数据
        int row = meetingDao.insertMeeting(entity);
        if (row != 1) {
            throw new EmosException("会议添加失败");
        }

        //开启审批工作流
        startMeetingWorkflow(entity.getUuid(), entity.getCreatorId().intValue(), entity.getDate(), entity.getStart());
    }

    private void startMeetingWorkflow(String uuid, int creatorId, String date, String start) {
        HashMap<String, Object> info = userDao.searchUserInfo(creatorId);
        JSONObject json = new JSONObject();
        json.set("url", recieveNotify);
        json.set("uuid", uuid);
        json.set("openId", info.get("openId"));
        json.set("code", code);
        json.set("date", date);
        json.set("start", start);
        String[] roles = info.get("roles").toString().split(",");
        if (!ArrayUtil.contains(roles, "总经理")) {
            Integer managerId = userDao.searchDeptManagerId(creatorId);
            json.set("managerId", managerId);
            Integer gmId = userDao.searchGmId();
            json.set("gmId", gmId);
            boolean bool = meetingDao.searchMeetingMembersInSameDept(uuid);
            json.set("sameDept", bool);
        }

        /*String url = workflow + "/workflow/startMeetingProcess";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application").body(json.toString()).execute();
        if (resp.getStatus() == 200) {
            json = JSONUtil.parseObj(resp.body());
            String instanceId = json.getStr("instanceId");
            HashMap<String, Object> param = new HashMap<>();
            param.put("uuid", uuid);
            param.put("instanceId", instanceId);
            int row = meetingDao.updateMeetingInstanceIdupdateMe(param);
            if (row != 1) {
                throw new EmosException("保存会议工作流实例ID失败");
            }
        }*/

        //替换代码
        String instanceId = IdUtil.simpleUUID();
        HashMap<String, Object> param = new HashMap<>();
        param.put("uuid", uuid);
        param.put("instanceId", instanceId);
        int row = meetingDao.updateMeetingInstanceId(param);
        if (row != 1) {
            throw new EmosException("保存会议工作流实例ID失败");
        }
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchMyMeetingListByPage(HashMap<String, Object> param) {
        ArrayList<HashMap<String, Object>> list = meetingDao.searchMyMeetingListByPage(param);
        String date = null;
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        HashMap<String, Object> resultMap = null;
        JSONArray array = null;
        for (HashMap<String, Object> map : list) {
            String temp = map.get("date").toString();
            //状态保存和状态转移
            if (!temp.equals(date)) {
                date = temp;
                resultMap = new HashMap<>();
                resultList.add(resultMap);
                resultMap.put("date", date);
                array = new JSONArray();
                resultMap.put("list", array);
            }
            array.put(map);
        }
        return resultList;
    }

    @Override
    public HashMap<String, Object> searchMeetingById(int id) {
        //会议信息
        HashMap<String, Object> map = meetingDao.searchMeetingById(id);
        //参会人员
        ArrayList<HashMap<String, Object>> list = meetingDao.searchMeetingMembers(id);
        map.put("members", list);
        return map;
    }

    @Override
    public void updateMeetingInfo(HashMap<String, Object> param) {
        int id = (int) param.get("id");
        String date = param.get("date").toString();
        String start = param.get("start").toString();
        String instanceId = param.get("instanceId").toString();
        HashMap<String, Object> oldMeeting = meetingDao.searchMeetingById(id);
        String uuid = oldMeeting.get("uuid").toString();
        int creatorId = Integer.parseInt(oldMeeting.get("creatorId").toString());

        int row = meetingDao.updateMeetingInfo(param);
        if (row != 1) {
            throw new EmosException("会议更新失败");
        }

        //删除之前的工作流
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.set("instanceId", instanceId);
        jsonObject.set("reason", "会议被修改");
        jsonObject.set("uuid", uuid);
        jsonObject.set("code", code);
        String url = workflow + "/workflow/deleteProcessById";
        HttpResponse response = HttpRequest.post(url).header("content-type", "application/json").body(jsonObject.toString()).execute();
        if (response.getStatus() != 200) {
            throw new EmosException("删除工作流失败");
        }*/

        //新建一个工作流
        startMeetingWorkflow(uuid, creatorId, date, start);
    }


}
